<?php
declare(strict_types=1);
/**
 * MineAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using MineAdmin.
 *
 * @Author X.Mo<root@imoi.cn>
 * @Link   https://gitee.com/xmo/MineAdmin
 */

namespace Plugin\Organization\Service;

use App\Exception\BusinessException;
use App\Http\Common\ResultCode;
use Plugin\Organization\Repository\RdOrganizeAreaRepository;
use App\Service\IService;
use Plugin\Organization\Repository\RdOrganizeProjLineRepository;

/**
 * 工区表服务类
 */
final class RdOrganizeAreaService extends IService
{
    public function __construct(
        protected readonly RdOrganizeAreaRepository $repository,
        protected readonly RdOrganizeProjLineRepository $projLineRepository,
        protected readonly RdOrganizeAreaStandService $areaStandService
    ) {}

    public function getAllowedUpdateData($data): array
    {
        return array_flip(['proj_line_id', 'name', 'abbr', 'addr', 'lat', 'lng', 'sort', 'status', 'remark', 'abstract']);
    }

    public function create(array $data): mixed
    {
        $projId = $data['proj_line_id'];
        $proj = $this->projLineRepository->findById($projId);
        if (!$proj) {
            throw new BusinessException(ResultCode::NOT_FOUND, '项目不存在');
        }
        return parent::create(array_merge($data, [
            'zone_id' => $proj->zone_id,
        ]));
    }

    /**
     * 根据项目线ID删除工区及其关联数据
     * @param mixed $id 项目线ID或ID数组
     */
    public function deleteByLineId(mixed $id): void
    {
        if (is_int($id)) {
            $id = [$id];
        }
        // 获取要删除的工区ID
        $ids = $this->repository->getQuery()->whereIn('proj_line_id', $id)->pluck('id')->toArray();
        if (!empty($ids)) {
            // 先删除关联的站点
            $this->areaStandService->deleteByAreaId($ids);
            // 再删除工区本身
            $this->deleteById($ids);
        }
    }
}